#!/bin/bash

################################################################################
# Nginx 负载均衡器 Docker 部署脚本
# 功能: 部署、管理 Nginx 容器
# 使用: ./deploy-nginx.sh [deploy|start|stop|restart|status|logs|update]
################################################################################

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 配置路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NGINX_CONFIG_DIR="/home/jd103/nginx-lb"
DOCKER_COMPOSE_FILE="${SCRIPT_DIR}/docker-compose.yml"
NGINX_CONFIG_FILE="${SCRIPT_DIR}/nginx.conf"

# 显示使用帮助
show_usage() {
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}Nginx 负载均衡器管理脚本${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""
    echo -e "${YELLOW}使用方法:${NC}"
    echo -e "  $0 ${GREEN}[命令]${NC}"
    echo ""
    echo -e "${YELLOW}可用命令:${NC}"
    echo -e "  ${GREEN}deploy${NC}   - 首次部署（创建目录、复制配置、启动容器）"
    echo -e "  ${GREEN}start${NC}    - 启动 Nginx 容器"
    echo -e "  ${GREEN}stop${NC}     - 停止 Nginx 容器"
    echo -e "  ${GREEN}restart${NC}  - 重启 Nginx 容器"
    echo -e "  ${GREEN}reload${NC}   - 重新加载 Nginx 配置（不重启容器）"
    echo -e "  ${GREEN}status${NC}   - 查看容器状态"
    echo -e "  ${GREEN}logs${NC}     - 查看 Nginx 日志"
    echo -e "  ${GREEN}update${NC}   - 更新配置文件并重启"
    echo -e "  ${GREEN}test${NC}     - 测试 Nginx 配置"
    echo -e "  ${GREEN}clean${NC}    - 停止并删除容器"
    echo ""
}

# 检查 Docker 是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        echo -e "${RED}错误: Docker 未安装${NC}"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
        echo -e "${RED}错误: Docker Compose 未安装${NC}"
        exit 1
    fi
}

# 创建必要的目录
create_directories() {
    echo -e "${YELLOW}创建配置目录...${NC}"
    sudo mkdir -p ${NGINX_CONFIG_DIR}/logs
    sudo mkdir -p ${NGINX_CONFIG_DIR}/ssl
    echo -e "${GREEN}✅ 目录创建成功${NC}"
}

# 复制配置文件
copy_config() {
    echo -e "${YELLOW}复制配置文件...${NC}"
    
    if [ ! -f "${NGINX_CONFIG_FILE}" ]; then
        echo -e "${RED}错误: nginx.conf 不存在${NC}"
        exit 1
    fi
    
    # 检查源文件和目标文件是否相同
    if [ "$(readlink -f ${NGINX_CONFIG_FILE})" = "$(readlink -f ${NGINX_CONFIG_DIR}/nginx.conf)" ]; then
        echo -e "${GREEN}✅ 配置文件已在目标位置，跳过复制${NC}"
    else
        sudo cp ${NGINX_CONFIG_FILE} ${NGINX_CONFIG_DIR}/nginx.conf
        echo -e "${GREEN}✅ 配置文件复制成功${NC}"
    fi
}

# 测试 Nginx 配置
test_config() {
    echo -e "${YELLOW}测试 Nginx 配置...${NC}"
    
    if docker ps -a | grep -q nginx-lb; then
        docker exec nginx-lb nginx -t
    else
        echo -e "${YELLOW}容器未运行，跳过配置测试${NC}"
    fi
}

# 部署
deploy() {
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}开始部署 Nginx 负载均衡器${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""
    
    check_docker
    create_directories
    copy_config
    
    echo -e "${YELLOW}启动容器...${NC}"
    cd ${SCRIPT_DIR}
    
    if command -v docker-compose &> /dev/null; then
        docker-compose up -d
    else
        docker compose up -d
    fi
    
    echo ""
    echo -e "${GREEN}✅ 部署完成！${NC}"
    echo ""
    
    sleep 3
    show_status
}

# 启动
start() {
    echo -e "${YELLOW}启动 Nginx 容器...${NC}"
    cd ${SCRIPT_DIR}
    
    if command -v docker-compose &> /dev/null; then
        docker-compose start
    else
        docker compose start
    fi
    
    echo -e "${GREEN}✅ 启动成功${NC}"
    show_status
}

# 停止
stop() {
    echo -e "${YELLOW}停止 Nginx 容器...${NC}"
    cd ${SCRIPT_DIR}
    
    if command -v docker-compose &> /dev/null; then
        docker-compose stop
    else
        docker compose stop
    fi
    
    echo -e "${GREEN}✅ 停止成功${NC}"
}

# 重启
restart() {
    echo -e "${YELLOW}重启 Nginx 容器...${NC}"
    cd ${SCRIPT_DIR}
    
    if command -v docker-compose &> /dev/null; then
        docker-compose restart
    else
        docker compose restart
    fi
    
    echo -e "${GREEN}✅ 重启成功${NC}"
    sleep 2
    show_status
}

# 重新加载配置
reload_config() {
    echo -e "${YELLOW}重新加载 Nginx 配置...${NC}"
    
    if ! docker ps | grep -q nginx-lb; then
        echo -e "${RED}错误: 容器未运行${NC}"
        exit 1
    fi
    
    # 复制新配置
    copy_config
    
    # 测试配置
    if docker exec nginx-lb nginx -t; then
        # 重新加载
        docker exec nginx-lb nginx -s reload
        echo -e "${GREEN}✅ 配置重新加载成功${NC}"
    else
        echo -e "${RED}❌ 配置测试失败，未重新加载${NC}"
        exit 1
    fi
}

# 显示状态
show_status() {
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}Nginx 容器状态${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""
    
    docker ps -a --filter name=nginx-lb --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
    
    echo ""
    
    if docker ps | grep -q nginx-lb; then
        echo -e "${GREEN}✅ 容器运行中${NC}"
        echo ""
        echo -e "${YELLOW}监听端口:${NC}"
        docker exec nginx-lb netstat -tlnp 2>/dev/null | grep nginx || echo "  80, 443, 9100, 9190 (host 模式)"
        echo ""
        echo -e "${YELLOW}访问地址:${NC}"
        echo -e "  API (域名):     ${GREEN}http://bigdata.data.jichuangmao.com${NC}"
        echo -e "  Console (域名): ${GREEN}http://bigdata-ui.data.jichuangmao.com${NC}"
        echo -e "  API (IP):       ${GREEN}http://10.1.1.103:9100${NC}"
        echo -e "  Console (IP):   ${GREEN}http://10.1.1.103:9190${NC}"
    else
        echo -e "${RED}❌ 容器未运行${NC}"
    fi
    
    echo ""
}

# 查看日志
show_logs() {
    echo -e "${YELLOW}查看 Nginx 日志 (Ctrl+C 退出)...${NC}"
    echo ""
    
    cd ${SCRIPT_DIR}
    
    if command -v docker-compose &> /dev/null; then
        docker-compose logs -f --tail=100
    else
        docker compose logs -f --tail=100
    fi
}

# 更新配置
update() {
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}更新 Nginx 配置${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""
    
    reload_config
    
    echo ""
    echo -e "${GREEN}✅ 配置更新完成${NC}"
}

# 清理
clean() {
    echo -e "${YELLOW}停止并删除容器...${NC}"
    
    read -p "确认删除容器？(y/N): " confirm
    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
        echo -e "${YELLOW}取消操作${NC}"
        exit 0
    fi
    
    cd ${SCRIPT_DIR}
    
    if command -v docker-compose &> /dev/null; then
        docker-compose down
    else
        docker compose down
    fi
    
    echo -e "${GREEN}✅ 容器已删除${NC}"
    echo -e "${YELLOW}注意: 配置文件和日志保留在 ${NGINX_CONFIG_DIR}${NC}"
}

# 主程序
main() {
    if [ $# -eq 0 ]; then
        show_usage
        exit 1
    fi
    
    ACTION=$1
    
    case ${ACTION} in
        deploy)
            deploy
            ;;
        start)
            start
            ;;
        stop)
            stop
            ;;
        restart)
            restart
            ;;
        reload)
            reload_config
            ;;
        status)
            show_status
            ;;
        logs)
            show_logs
            ;;
        update)
            update
            ;;
        test)
            test_config
            ;;
        clean)
            clean
            ;;
        *)
            echo -e "${RED}错误: 未知命令 '${ACTION}'${NC}"
            echo ""
            show_usage
            exit 1
            ;;
    esac
}

# 执行主程序
main "$@"
